
#include "jxos_config.h"
#if (JXOS_TASK_ENABLE == 1)
#include "kernel/jxos_task.h"
#endif

#if (JXOS_SYS_SERVICE_SOFTWARE_TIMER_TASK_ENABLE == 1)
#include "driver/sim_timer.h"

extern void sys_svc_software_timer_init_callback(void);

static uint8_t sim_timer_index_count;
uint16_t sys_svc_software_timer_tick_counter;

#if (JXOS_Compiler_optimization_1 == 1)
#if (JXOS_TASK_ENABLE == 1)
static void software_timer_task(void)
#else
void sys_software_timer_task(void)
#endif
#else
static void software_timer_task(uint8_t task_id, void * parameter)
#endif
{
	uint16_t temp_counter;
	if(sys_svc_software_timer_tick_counter > 0){
		temp_counter = sys_svc_software_timer_tick_counter;
		sys_svc_software_timer_tick_counter = 0;
		sim_timer_tick_hander(temp_counter);
	}
}

void sys_software_timer_task_init(void)
{
	sys_svc_software_timer_init_callback();
	
	sys_svc_software_timer_tick_counter = 0;
	sim_timer_index_count = 0;

	sim_timer_init();

#if (JXOS_TASK_ENABLE == 1)
	jxos_task_create(software_timer_task, "swt_t", 0);
#endif
}

/*******************************************************/
void* sys_svc_software_timer_new(void)
{
	uint8_t index = 0;
	if(sim_timer_index_count < SWTIMER_MAX){
		sim_timer_index_count++;
		index = sim_timer_index_count;
	}
	return (void*)index;
}

void sys_svc_software_timer_set_time(void* swtime, uint16_t time)
{   
	uint8_t i = (uint8_t)swtime;
	if((i <= sim_timer_index_count)&&(i != 0)){
		i--;
		time = time/TIMER_CONSTANT_INTERVAL_MS;
		sim_timer_set_timeout(i, time);
	}
}

void sys_svc_software_timer_start(void* swtime)
{
	uint8_t i = (uint8_t)swtime;
	if((i <= sim_timer_index_count)&&(i != 0)){
		i--;
		sim_timer_start(i);
	}
}

void sys_svc_software_timer_stop(void* swtime)
{
	uint8_t i = (uint8_t)swtime;
	if((i <= sim_timer_index_count)&&(i != 0)){
		i--;
		sim_timer_stop(i);
	}
}

void sys_svc_software_timer_restart(void* swtime)
{
	uint8_t i = (uint8_t)swtime;
	if((i <= sim_timer_index_count)&&(i != 0)){
		i--;
		sim_timer_restart(i);
	}
}

bool_t sys_svc_software_timer_check_running(void* swtime)
{
	uint8_t i = (uint8_t)swtime;
	if((i <= sim_timer_index_count)&&(i != 0)){
		i--;
		i = sim_timer_check_running(i);
	}
	return (bool_t)i;
}

bool_t sys_svc_software_timer_check_overtime(void* swtime)
{
	uint8_t i = (uint8_t)swtime;
	if((i <= sim_timer_index_count)&&(i != 0)){
		i--;
		i = sim_timer_check_overtime(i);
	}
	return (bool_t)i;
}

#if (JXOS_ENENT_ENABLE == 1)&&(JXOS_Compiler_optimization_2 == 0)
void sys_svc_software_timer_tick_handler(void)
{
	sys_svc_software_timer_tick_counter++;
}
#endif

#endif
